<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书籍点击量排名 - 纵横小说推荐榜数据可视化平台</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/chart-styles.css') }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
</head>
<body>
    <!-- 顶部区域 -->
    <header class="header">
        <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo" class="logo">
        <h1 class="system-title">纵横小说推荐榜数据可视化平台</h1>
    </header>

    <!-- 左侧导航栏 -->
    <nav class="sidebar">
        <a href="/" class="nav-item">
            <i class="fas fa-book-open fa-fw"></i>
            <span>图书列表</span>
        </a>
        <a href="/charts" class="nav-item">
            <i class="fas fa-chart-pie fa-fw"></i>
            <span>书籍类别分布</span>
        </a>
        <a href="/bar-chart" class="nav-item">
            <i class="fas fa-chart-bar fa-fw"></i>
            <span>类别点击量分析</span>
        </a>
        <a href="/line-chart" class="nav-item">
            <i class="fas fa-chart-line fa-fw"></i>
            <span>字数与推荐数关系</span>
        </a>
        <a href="/boxplot" class="nav-item">
            <i class="fas fa-chart-simple fa-fw"></i>
            <span>状态与周推荐数</span>
        </a>
        <a href="/ranking-chart" class="nav-item active">
            <i class="fas fa-trophy fa-fw"></i>
            <span>书籍点击量排名</span>
        </a>
    </nav>

    <!-- 主内容区 -->
    <main class="main-content">
        <h2 class="page-title">书籍点击量排名</h2>

        <div class="chart-container">
            <div class="chart-header">
                <h3 class="chart-title">
                    <i class="fas fa-trophy"></i>
                    点击量排名前20的书籍
                </h3>
                <div class="chart-actions">
                    <div class="chart-filter">
                        <label for="sortOrder">排序方式：</label>
                        <select id="sortOrder" class="filter-select">
                            <option value="desc">从高到低</option>
                            <option value="asc">从低到高</option>
                        </select>
                    </div>
                    <button id="downloadBtn" class="action-button">
                        <i class="fas fa-download"></i>
                        <span>下载图表</span>
                    </button>
                    <button id="refreshBtn" class="action-button">
                        <i class="fas fa-sync-alt"></i>
                        <span>刷新数据</span>
                    </button>
                </div>
            </div>

            <div class="chart-description">
                <i class="fas fa-info-circle"></i>
                <p>此图表展示了纵横小说推荐榜中点击量排名前20的书籍，不同颜色代表不同的书籍类别，可以通过排序方式切换查看不同的排序结果。</p>
            </div>

            <div id="loadingIndicator" class="loading">
                <div class="loading-spinner"></div>
            </div>

            <div id="chart" class="chart"></div>
        </div>

        <div class="chart-container">
            <div class="chart-header">
                <h3 class="chart-title">
                    <i class="fas fa-table"></i>
                    类别分布统计
                </h3>
            </div>

            <div class="stats-grid" id="categoryStats">
                <!-- 类别统计卡片将通过JavaScript动态填充 -->
            </div>
        </div>
    </main>

    <script>
        // 初始化ECharts实例
        var chartDom = document.getElementById('chart');
        var myChart = echarts.init(chartDom);

        var rawData = [];
        var categoryColors = {};

        // 显示加载状态
        function showLoading() {
            document.getElementById('loadingIndicator').style.display = 'flex';
        }

        // 隐藏加载状态
        function hideLoading() {
            document.getElementById('loadingIndicator').style.display = 'none';
        }

        // 获取图表数据
        async function fetchChartData() {
            showLoading();

            try {
                const response = await fetch('/api/books-ranking');
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }

                rawData = await response.json();

                // 分配颜色给不同类别
                const categories = [...new Set(rawData.map(item => item.category))];
                const colorList = [
                    '#1890ff', '#13c2c2', '#52c41a', '#faad14', '#f5222d',
                    '#722ed1', '#eb2f96', '#fa8c16', '#a0d911', '#fadb14',
                    '#2f54eb', '#fa541c', '#391085', '#9254de', '#36cfc9'
                ];

                categories.forEach((category, index) => {
                    categoryColors[category] = colorList[index % colorList.length];
                });

                renderChart('desc');
                updateCategoryStats();
            } catch (error) {
                console.error('获取数据失败:', error);
                myChart.showLoading({
                    text: '数据加载失败，请刷新重试',
                    maskColor: 'rgba(255, 255, 255, 0.8)',
                    textColor: '#ff4d4f'
                });
            } finally {
                hideLoading();
            }
        }

        // 渲染排名图表
        function renderChart(sortOrder) {
            // 排序数据
            const sortedData = [...rawData].sort((a, b) => {
                return sortOrder === 'desc' ? b.value - a.value : a.value - b.value;
            });

            // 准备数据
            const names = sortedData.map(item => item.name);
            const values = sortedData.map(item => item.value);
            const categories = sortedData.map(item => item.category);

            // 配置选项
            const option = {
                title: {
                    text: '点击量排名前20的书籍',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function(params) {
                        const data = params[0];
                        return `书名: ${data.name}<br/>` +
                               `类别: ${categories[data.dataIndex]}<br/>` +
                               `点击量: ${data.value.toLocaleString()} 次`;
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    name: '点击量',
                    axisLabel: {
                        formatter: function(value) {
                            return value >= 10000 ? (value / 10000).toFixed(1) + '万' : value;
                        }
                    }
                },
                yAxis: {
                    type: 'category',
                    data: names,
                    axisLabel: {
                        interval: 0,
                        rotate: 0,
                        formatter: function(value) {
                            return value.length > 10 ? value.substring(0, 10) + '...' : value;
                        }
                    }
                },
                series: [
                    {
                        name: '点击量',
                        type: 'bar',
                        data: values,
                        itemStyle: {
                            color: function(params) {
                                return categoryColors[categories[params.dataIndex]];
                            }
                        },
                        label: {
                            show: true,
                            position: 'right',
                            formatter: function(params) {
                                return params.value >= 10000 ?
                                    (params.value / 10000).toFixed(1) + '万' :
                                    params.value;
                            }
                        }
                    }
                ]
            };

            myChart.setOption(option);
        }

        // 更新类别统计
        function updateCategoryStats() {
            // 按类别分组
            const categoryData = {};
            rawData.forEach(item => {
                if (!categoryData[item.category]) {
                    categoryData[item.category] = {
                        count: 0,
                        totalClicks: 0
                    };
                }
                categoryData[item.category].count++;
                categoryData[item.category].totalClicks += item.value;
            });

            // 创建统计卡片
            const statsContainer = document.getElementById('categoryStats');
            statsContainer.innerHTML = '';

            Object.keys(categoryData).forEach(category => {
                const data = categoryData[category];
                const avgClicks = (data.totalClicks / data.count).toFixed(0);

                const card = document.createElement('div');
                card.className = 'stats-card';
                card.innerHTML = `
                    <div class="stats-icon" style="background-color: ${categoryColors[category]}">
                        <i class="fas fa-book"></i>
                    </div>
                    <div class="stats-content">
                        <div class="stats-title">${category}</div>
                        <div class="stats-value">${data.count} 本</div>
                        <div class="stats-desc">平均点击量: ${avgClicks >= 10000 ? (avgClicks / 10000).toFixed(1) + '万' : avgClicks}</div>
                    </div>
                `;

                statsContainer.appendChild(card);
            });
        }

        // 下载图表
        document.getElementById('downloadBtn').addEventListener('click', function() {
            const link = document.createElement('a');
            link.download = '书籍点击量排名.png';
            link.href = myChart.getDataURL({
                type: 'png',
                pixelRatio: 2,
                backgroundColor: '#fff'
            });
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        });

        // 排序方式切换
        document.getElementById('sortOrder').addEventListener('change', function() {
            renderChart(this.value);
        });

        // 刷新数据
        document.getElementById('refreshBtn').addEventListener('click', fetchChartData);

        // 响应窗口大小变化
        window.addEventListener('resize', function() {
            myChart.resize();
        });

        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', fetchChartData);
    </script>
</body>
</html>
